<template>
	<view class="box">
		<view class="beforeSpeBox" v-if="action=='beforeSub'">
			<view class="beforeSpe"></view>
			<br>
			请刷卡....
			<view v-if="isWorkdays" class="selfDo" @click="selfDo()">手动打卡</view>
		</view>
		<view class="waitCheck"  v-if="action=='wait'">
			<!-- <picker bindchange="PickerChange" v-model="index" :range="picker">
				<view class="picker">
					{{index?picker[index]:'请选择...'}}
				</view>
			</picker> -->
			<image src="../../static/noTaskBg.png" style="width: calc(100% - 60px);margin-top: 20%;" mode="aspectFit"></image>
			<view class="warnTbn"  @click="warnCheck()">状态异常，手动巡检</view>
			<view class="uttonzs" @click="actionCheck()" :style="[{animationDelay: '0.2s'}]">开始巡检</view>
		</view>
		<view class="detailForm" v-if="action=='sub'">
			<view class="detailItem" v-if="!isWarn">
				<view class="detailLabel">
					卡号：
				</view>
				<input :disabled="true"  type="text" v-model="cardName" class="detailInput" placeholder="请输入卡号"/>
				<!-- <input :disabled="cardWarn"  type="text" v-model="cardId" class="detailInput" placeholder="请输入卡号"/> -->
			</view>
			<view class="detailItem">
				<view class="detailLabel">
					点位：
				</view>
				<picker :disabled="cardWarn" mode="selector" class="detailInput" v-model="pointIndex" :range="pointList.map(item=>item.label)" @change="changePointer">
					<view class="picker">
						{{(Number(pointIndex)>-1)?pointList.map(item=>item.label)[pointIndex]:'未选择'}}
					</view>
				</picker>
				<!-- <input type="text" value="" class="detailInput" placeholder="请选择点位"/> -->
			</view>
			<!-- <view class="detailItem">
				<view class="detailLabel">
					状态：
				</view>
				<input disabled="disabled" type="text" v-model="status" class="detailInput" @click="selectStatus()" placeholder="请选择点位"/>
				<view class="selectBox animation-slide-bottom" :style="[{animationDelay: '0.1s'}]" v-if="selectStatusFlag">
					<view class="selectItem" @click="changeStatus('1')">正常</view>
					<view class="selectItem" @click="changeStatus('2')">异常</view>
				</view>
			</view> -->
			<view class="detailItem" style="border-bottom: none;">
				<view class="detailLabel">
					备注：
				</view>
				<textarea v-model="remark" type="text" value="" class="detailInput"></textarea>
			</view>
			<view class="btns">
				<view class="blueBtn" @click="subData()">提交</view>
			</view>
		</view>
	</view>
</template>

<script>
	import Request from '@/common/luch-request/index.js'
	const http = new Request()
	export default {
		name:'workcard',
		data() {
			return {
				nfcClose:true,
				NFCAdapter:undefined,
				action:'beforeSub',// wait beforeSub  sub
				selected:'2',
				cardId:'',
				cardName:'',
				cardNo:'',
				remark:'值班签到',
				selectStatusFlag:false,
				status:'',
				cardWarn:true,//是否允许编辑
				picker: [],
				index:null,
				isWarn:false,//是否异常打卡
				pointList:[],//点位列表，异常时候可以手动选择
				pointName:'',
				pointId:'',
				pointIndex:-1,
				isWorkdays:false,//上班的早上吗？
			}
		},
		mounted() {
			 this.getPoints();
			 this.cloaseNfc();
			 
			 // 初始默认开始异常无任务巡检并记录
			 this.isWarn = true;
			 this.cardWarn = false;
			 this.actionCheck();
			 
			 this.$http.get('/inspect/insClasses/getIsNotWork?data='+new Date().toLocaleDateString('zh-cn').split('/').join('-')).then(res=>{
				 let isAm = new Date().getHours()<12;
				 this.isWorkdays =  res.data == '0' && isAm;//0:上班 1：不上班
				 console.log('获取到的日期：',res);
			 })
			 // http.get('https://apis.tianapi.com/jiejiari/index?key=3950b924e669b8044168c5a91787fb4e&type=0&date='+new Date().toLocaleDateString('zh-cn').split('/').join('-')).then(res=>{
				//  let isAm = new Date().getHours()<12;//是不是早上
				//  this.isWorkdays = res.data.result.list[0].isnotwork == '0' && isAm;//0:上班 1：不上班
				//  console.log('上班的早上？：',this.isWorkdays)
			 // })
		},
		onHide() {
			console.log('退出work')
			this.cloaseNfc();
		},
		beforeDestroy() {
			console.log('销毁work0')
			this.cloaseNfc();
			
		},
		onUnload() {
			console.log('销毁work')
			this.cloaseNfc();
		},
		methods: {
			changePointer(val){
				this.pointIndex = val.detail.value
				this.pointId = this.pointList[val.detail.value].value
			},
			async getCardInfo(id){
				let _this = this;
				await this.$http.get('/inspect/insPoint/queryByCardNo',{
					params:{cardNo:id || this.cardNo }
				}).then(res=>{
					if(res.data.success){
						_this.cardId = res.data.result.cardId;
						_this.cardName = res.data.result.cardName || res.data.result.cardNo || '异常';
						let zindex=-1;
						_this.pointList.forEach((ii,index)=>{
							if(ii.label == res.data.result.pointName){
								zindex = index
							}
						})
						_this.pointIndex = zindex
						_this.pointId = _this.pointList[zindex].value
						console.log('回填：',_this.pointIndex)
					}else{
						_this.$tip.toast(res.data.message);
						_this.action = 'beforeSub';
					}
				})
			},
			getPoints(){
				let _this = this;
				this.$http.get('/inspect/insPoint/list?pageNo=1&pageSize=9999')
					.then(res=>{
						if(res.data.success){
						 _this.pointList = res.data.result.records.map(item=>{
							 return {
								 value:item.id,
								 label:item.pointName
							 }
						 })
						}
					})
			},
			PickerChange(e) {
			  console.log(e);
			  this.setData({
			    index: e.detail.value
			  })
			},
			warnCheck(){
				this.isWarn = true;
				this.cardWarn = false;
				this.actionCheck();
			},
			cloaseNfc(){
				if(this.NFCAdapter){
					this.NFCAdapter.offDiscovered(this.discoverHandler)
					this.NFCAdapter.stopDiscovery()
					this.NFCAdapter = null
				}
			},
			actionCheck(){
				this.action = 'beforeSub'
				this.$tip.toast("请将设备放入识别区NFC")
				try{
					this.cloaseNfc();
				}catch(e){
					//TODO handle the exception
				}
				this.NFCAdapter = wx.getNFCAdapter();
				this.NFClistener();
			},
			changeStatus(val){
				let obj=['','正常','异常']
				this.status = obj[val];
				this.selectStatusFlag = false;
			},
			selectStatus(){
				this.selectStatusFlag = !this.selectStatusFlag;
			},
			// 手动打卡
			async selfDo(){
				await this.getCardInfo('3bf3b19e');
				let subData={
					cardId:this.cardId,
					pointId:this.pointId,
					insStatus:'1',
					remark:this.remark
				}
				subData.isConnect = '是';
				if(!subData.pointId){
					return this.$tip.toast('请查看点位是否正常')
				}
				let _this = this;
				this.$http.post('/inspect/insTaskRecord/add',subData).then(res=>{
					if(res.data.success){
						_this.$tip.toast('提交成功！');
					}else{
						_this.$tip.toast('提交异常！')
					}
					
				})
			},
			subData(){
				let subData = {};
				if(this.isWarn){//异常打卡
					subData={
						pointId:this.pointId,
						insStatus:this.status!="正常"?'2':'1',
						remark:this.remark
					}
				}else{
					subData={
						cardId:this.cardId,
						pointId:this.pointId,
						insStatus:this.status!="正常"?'2':'1',
						remark:this.remark
					}
				}
				subData.isConnect = '是';
				console.log(subData)
				if(!subData.pointId){
					return this.$tip.toast('请查看点位是否正常')
				}
				let _this = this;
				this.$http.post('/inspect/insTaskRecord/add',subData).then(res=>{
					if(res.data.success){
						_this.$tip.toast('提交成功！');
						_this.action = 'wait'
					}else{
						_this.$tip.toast('提交异常！')
					}
					
				})
			},
			change(val){
				console.log(val)
			},
			NFClistener(){
				let _this = this;
				this.NFCAdapter.startDiscovery({
				  success: () => {
				    _this.$tip.alert("请将设备放入识别区NFC")
				    // 监听 NFC 标签
				    _this.NFCAdapter.onDiscovered(this.discoverHandler)
				  },
				  fail: error => {
					  console.log('error',error)
				    // this.setData({
				    //   msgTitle: '请重试'
				    // })
					if(error.errMsg=='startDiscovery:fail:NFC discovery already started'){
						 _this.NFCAdapter.onDiscovered(this.discoverHandler)
					}
					_this.$tip.alert("请重试")
				    console.error(error)
				  }
				})
			},
			/**
			 * 监听回调
			 */
			discoverHandler(callback) {
				let _this = this;
			  console.log('==================== START ====================')
			  console.log('onDiscovered callback=>', callback)
			  const arr = [0x01, 0x01, 0x01, 0x01];
			const writeBuffer = new Uint8Array(arr);
			  console.log('卡片的Idd',callback.id);
			  console.log('卡片的Idd',callback.id.buffer);
			  try{
				  let cId = this.changeType(callback.id)
				_this.cardNo = cId || ''
				if(_this.cardNo != '3bf3b19e'){
					return _this.$tip.toast('当前场景非一号会议室！');
				}
				_this.action = 'sub';
				// _this.cloaseNfc();
				_this.getCardInfo();
			  }catch(e){}
			},
			changeType(buffer){
			 return Array.prototype.map.call(new Uint8Array(buffer),x => ('00'+x.toString(16)).slice(-2)).join('')
			},
		}
	}
</script>

<style scoped>
	.box{
		padding: 12px;
		padding-bottom: 60px;
	}
	page,.showDom{
		width: 100%;
		height: 100%;
	}
	.detailForm{
		width: 100%;
		height: 100%;
		background-color: #fff;
		border-radius: 8px;
		box-shadow: 0px 0px 5px rgba(0,0,0,.1);
		padding: 20px;
		font-size: 13px;
		line-height: 38px;
	}
	.btns{
		display: flex;
		align-items: center;
		justify-content: center;
		height: 52px;
		margin-top: 30px;
	}
	.blueBtn{
		padding: 0 22px;
		border-radius: 4px;
		line-height: 30px;
		display: inline-block;
		color: #fff;
		font-size: 14px;
		background-color: rgba(19, 202, 156, 1);
	}
	.selectBox{
		width: 160px;
		max-height: 150px;
		overflow: auto;
		border-radius: 4px;
		box-shadow: 0 0 5px rgba(0,0,0,.1);
		background: #fff;
		position: absolute;
		z-index: 222;
		top: 43px;
		left: 60px;
	}
	.selectItem{
		border-bottom: 1px solid rgba(0,0,0,.02);
		line-height: 30px;
		padding-left: 12px;
	}
	.detailLabel{
		width: 60px;
		color: #000000;
	}
	.detailInput{
		width: calc(100% - 60px);
		height: 38px;
		color: #555;
		font-size: 12px;
	}
	textarea.detailInput{
		height: 80px;
		line-height: 20px;
		border: 1px solid rgba(0,0,0,.1);
		border-radius: 2px;
		margin-top: 6px;
		padding: 6px;
	}
	.detailItem{
		border-bottom: 1px solid rgba(0,0,0,.04);
		display: flex;
		position: relative;
	}
	.waitCheck,.box{
		width:100%;
		height: 100%;
	}
	.waitCheck{
		display: flex;
		align-items: flex-start;
		justify-content: center;
		align-content: flex-start;
		flex-wrap: wrap;
		position: relative;
		background-color: #fff;
		border-radius: 8px;
	}
	.warnTbn{
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		bottom: 78px;
		font-size: 12px;
		color: rgba(102, 102, 102, 1);
	}
	.uttonzs{
		background-color: rgba(19, 202, 156, 1);
		box-shadow: 0 10px 16px -6px rgba(19, 202, 156, 0.44);
		padding: 0 12px;
		color: white;
		font-size: 15px;
		font-weight: bold;
		width: calc(100% - 24px);
		border-radius: 6px;
		height: 44px;
		line-height: 44px;
		text-align: center;
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		bottom: 20px;
	}
	.beforeSpeBox{
		width: 100vw;
		height: 90vh;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
	}
	.beforeSpe{
		height: 20px;
		background-color: rgba(19, 202, 156, 1);
		border-radius: 6px;
		animation:fullWidth 3s linear infinite;
		margin-bottom: 12px;
	}
	@keyframes fullWidth{
		from{
			width:0px
		}
		to{
			width: 200px;
		}
	}
	.selfDo{
		position: absolute;
		bottom: 160rpx;
		left: 50%;
		transform: translateX(-50%);
		display: inline-block;
		padding: 12rpx 24rpx;
		background-color: #1CBBB4;
		color: #fff;
		border-radius: 8rpx;
	}
</style>
